using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Emlyn.Common.Data.SqlServer.SqlManagers;
using System.Data.SqlClient;
using Emlyn.Common.Tools.Encryption;
using Emlyn.Common.Tools.BusinessLayer;

namespace Emlyn.Website.Users
{
    public class UserQuery: BaseQuery<User, Guid, UserDataLayer>
    {
        public UserQuery()
            : base(new UserDataLayer())
        {
        }

        public User GetUserByUserName(string aUserName)
        {
            return ConstructInstanceFromDataSet(_dl.GetUserByUserName(aUserName));
        }

        public IList<User> GetUsersForWebsiteCode(string aWebsiteCode)
        {
            return ConstructInstancesFromDataSet(_dl.GetUsersByWebsiteCode(aWebsiteCode));
        }

        public void CheckCredentials(User aUser, string aWebsiteCode)
        {
            User aSavedUser = GetUserByUserName(aUser.UserName);

            if (aSavedUser == null)
                throw new UnknownUserException();

            if (aSavedUser.HashedPassword != aUser.HashedPassword)
                throw new IncorrectPasswordException();

            if (aSavedUser.WebsiteCode != aWebsiteCode)
                throw new NoWebsiteAccessException();
        }

        protected override User ConstructInstanceFromRow(DataRow lrow)
        {
            User luser = new User((Guid)lrow["UserID"]);
            luser.UserName = Convert.ToString(lrow["UserName"]).Trim();
            luser.HashedPassword = Convert.ToString(lrow["Password"]).Trim();
            luser.AuthLevel = (GlobalAuthLevel)Enum.ToObject(typeof(GlobalAuthLevel), lrow["AuthLevel"]);
            luser.Email = Convert.ToString(lrow["Email"]).Trim();
            luser.ValidationCode = Convert.ToString(lrow["ValidationCode"]);
            luser.WebsiteCode = Convert.ToString(lrow["WebsiteCode"]).Trim();
            return luser;
        }
    }
}
